package com.samsung.sharepoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

//This Activity can be opened by either intent passed from "ChatList.java" (if the user has to initiate the chat)
// OR the intent can be passed from "listenService.java" (The Service class that listens to message).
// The second case happens when the chat is initiated because of message sent by ither device

public class SampleTCP extends Activity {
	
	Intent intent,intent1,file_server_intent,file_client_intent;
	Button submit,sendfile;
	EditText msg;
	EditText chatBox;
	String temp, myName,ServerIP="";
	SharedPreferences spref;
	Intent i;
	String fpath;
	String FirstMsgSenderIP="";
	int activityMsgCount=0;
	String firstMessage="";
	ScrollView SView;
	TextView TVname;
	boolean startedFromAnotherDevice=false;
	
	private BroadcastReceiver IPReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	// "activityMsgCount" is to keep the check if the message to be displayed is the first message received for chat
        	if(activityMsgCount!= 0){
        		if(!intent.getStringExtra("Message").equals(""))
        		{
        			temp=temp+"\n" + "";
        		}
        		temp= temp + intent.getStringExtra("Message");
            }
        	else{
        		temp= temp + "\n" + intent.getStringExtra("Message");
        	}
    		Log.d("SampleTCP","Brpoapdcast caled" + temp);
    		Log.d("SampleTCP","In EditText to display " + temp);
	    	if(!temp.isEmpty()){
				chatBox.setText(temp);
			}
	    	activityMsgCount++;
		}
    }; 
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // simple handler test (does not send messages to RcvMessages activity
            String obj = (String) msg.obj;
           Toast.makeText(getApplicationContext(), obj, Toast.LENGTH_SHORT).show();
            Log.i("handleMessge", "obj: " + obj);  
        }
    };
    private Handler Exception_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // simple handler test (does not send messages to RcvMessages activity
            String obj = (String) msg.obj;
            new AlertDialog.Builder(SampleTCP.this)
    	    .setTitle("Connection Lost")
    	    .setMessage(obj)
    	    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    	        	public void onClick(DialogInterface dialog, int whichButton) {
    	        		//Stop all services (except listenService.java)
    	        		Intent intent1=new Intent("com.samsung.sharepoint.serviceclientclass");
    	            	stopService(intent1);
    	            	Intent file_client_intent=new Intent("com.samsung.sharepoint.fileclientservice");
    	            	stopService(file_client_intent);
    	            	Intent chat_server_intent=new Intent("com.samsung.sharepoint.serviceclass");
    	            	stopService(chat_server_intent);
    	            	Intent file_server_intent=new Intent("com.samsung.sharepoint.fileserverservice");
    	            	stopService(file_server_intent);
    	            	System.exit(0);
    	        	}
    	    })
    	    .create()
    	    .show();;  
        }
    };
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Register the receiver for broadacst sent by ServiceClass (which listens to received messages)
		registerReceiver(IPReceiver, new IntentFilter(ServiceClass.BROADCAST_ACTION));
		setContentView(R.layout.chat);
		Log.d("SampleTCP","onCreate of SampleTCP");
		spref = getSharedPreferences("abc",MODE_PRIVATE);
		//Get the device user name
		myName=spref.getString("name","Anonymous Pundit");
		//Get the intent responsible for opening of this Activity
		i=getIntent();
		//This is the IP of the device that initiate chat
		FirstMsgSenderIP=i.getStringExtra("FirstMsgSenderIP"); 
		// This is the IP of the device that is clicked in ChatList 
		ServerIP= i.getStringExtra("AvailableDeviceIP"); 
		//Create an intent for File Server Service, which listens for File Transfer Request
        file_server_intent=new Intent("com.samsung.sharepoint.fileserverservice");
		file_server_intent.putExtra("option","case1");
		if(ServerIP != null && !ServerIP.isEmpty())
			file_server_intent.putExtra("serverip",ServerIP);
		else
			file_server_intent.putExtra("serverip",FirstMsgSenderIP);
		file_server_intent.putExtra("handler", new Messenger(handler));
		startService(file_server_intent);
	}
	
	
	public void onStart(){
		super.onStart();
		temp="";
		chatBox=(EditText)findViewById(R.id.recMsg); // The existing chat 
		msg=(EditText)findViewById(R.id.sendMsg); //The new message typed
		SView = (ScrollView)findViewById(R.id.scroller); //Scroll View to scroll the chat
		TVname = (TextView)findViewById(R.id.textView1); //TextView that displays "Talking to" message
		Intent chatList = getIntent(); //get the intent responsible for opening of this activity
		TVname.setText("Talking to " + chatList.getStringExtra("SampleTCP_UserName_Receiver")); 
		firstMessage=i.getStringExtra("FirstMessage"); 
		// firstMessage is not null if the Activity is opened because of incoming message from another device
		// i.e. SampleTCP is opened because of the intent passed from "ServiceClass.java", the class that listens to message
		// firstMessage is the first Message sent by other device
		if(firstMessage!=null && !firstMessage.isEmpty()){
		 		startedFromAnotherDevice=true; 
		 		temp = temp + firstMessage; 
				chatBox.setText(temp);
				SView.post(new Runnable() {
					
					public void run() {
						// To keep the most recent chat on top, and previous talk to scroll up
						SView.smoothScrollTo(0, chatBox.getBottom());
					}
				});
			}
	}
	
	
	public void onResume(){
		super.onResume();
		Log.d("SampleTCP","onResume()");
		submit=(Button)findViewById(R.id.send);
		submit.setOnClickListener(new OnClickListener(){
			
			public void onClick(View arg0) {
				if(startedFromAnotherDevice){
					// To notify that other messages received are of aldready existing chat 
					 startedFromAnotherDevice=false;
				   }
		   
		    	temp = temp + "\n" + myName +":"+ msg.getText() ; //Append infron the UsernName before the new message
				chatBox.setText(temp);
				SView.post(new Runnable() {
				public void run() {
						// To keep the most recent chat on top, and previous talk to scroll up
						SView.smoothScrollTo(0, chatBox.getBottom());
					}
				});

				sendMessage();
				msg.setText("");
			}
		});
		
		sendfile=(Button)findViewById(R.id.fileSend);
		sendfile.setOnClickListener(new OnClickListener(){
			//For File Transfer
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Log.d("SampleTCP","SendFile Button Clicked");
				Intent intent = new Intent(SampleTCP.this,attach.class);
				
				String ServerIP = i.getStringExtra("ServerIP");
				Log.d("SampleTCP","File to send to"+ServerIP);
				intent.putExtra("ServerIP",ServerIP);
				
				startActivityForResult(intent, 1);
			


			}
		});
	}
	
	//To display alert box to confirm file transfer. The Activity Result is returned from "attach.java"
	protected void onActivityResult(int requestCode,int resultCode,Intent data)
	{
		fpath=data.getStringExtra("abc");
		if(resultCode==1)
		{
			new AlertDialog.Builder(SampleTCP.this)
    	    .setTitle("File Request")
    	    .setMessage("Do You Really want to send file "+fpath)
    	    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    	        	public void onClick(DialogInterface dialog, int whichButton) {
    	        		file_client_intent=new Intent("com.samsung.sharepoint.fileclientservice");
    	    			file_client_intent.putExtra("file_path",fpath);
    	    			file_client_intent.putExtra("handler", new Messenger(handler));
    	    			file_client_intent.putExtra("exhandler", new Messenger(Exception_handler));
    	    			file_client_intent.putExtra("ServerIP",ServerIP);
    	    			startService(file_client_intent);
    	        		
    	        	}
    	    })
    	    .setNegativeButton("No", new DialogInterface.OnClickListener() {
    	        	public void onClick(DialogInterface dialog, int whichButton) {
    	        		Toast.makeText(SampleTCP.this,"File Sending Cancelled",Toast.LENGTH_SHORT).show();
    	        	}
    	    })
    	    .create()
    	    .show();
		}
	}
	
	
	@Override
	protected void onStop(){
		super.onStop();
	}
	
	@Override 
	protected void onDestroy(){
		unregisterReceiver(IPReceiver);
		super.onDestroy();
	}
	
	private void sendMessage(){
		String text=msg.getText().toString();
		intent1=new Intent("com.samsung.sharepoint.serviceclientclass");
		intent1.putExtra("Message", myName + ":" + text);
	
		if( ServerIP != null && ServerIP != ""){
			intent1.putExtra("ServerIP", ServerIP);
			Log.d("SampleTCP","List Item Device Clicked for opening Activity");
			Log.d("SampleTCP", "Device IP is " + ServerIP );
		}
			
		else {
			intent1.putExtra("ServerIP", FirstMsgSenderIP);
			Log.d("SampleTCP","FirstMessageSenderIP= " + FirstMsgSenderIP);
			Log.d("SampleTCP", "Activity opened through message from other device and so ListItemIP is = " + ServerIP);
		}
			
		if(!text.isEmpty())
			startService(intent1);
	}
}
